use std::collections::HashMap;

use serde_json::json;
use tauri::{http::{HeaderMap, HeaderName, HeaderValue}, AppHandle};

#[path ="../service/mod.rs"]
mod service;

#[path ="../util/http.rs"]
mod http;
#[path ="../util/data_util.rs"]
mod data_util;

#[path ="../util/snow_flake.rs"]
mod snow_flake;
// #[tauri::command]
// pub fn file_separator() -> String{
//     let s = std::path::MAIN_SEPARATOR_STR;
//     s.to_string()
// }

#[tauri::command]
pub fn snow_flake_id()->u128{
    let next_id = snow_flake::snow_flake_id();
    next_id
}

#[tauri::command]
pub fn uuid()->String{
    let uuid = uuid::Uuid::new_v4();
    let rand32b = uuid.simple().to_string().to_uppercase();
    rand32b
}

#[tauri::command]
pub fn http_headers(mac: Option<&str>,term:Option<&str>)->String{
    let headers = http::assemble_header(mac,term);
    let mut json_headers = json!({});

    for (name, value) in headers.iter() {
        let name_str = name.as_str();
        let value_str = value.to_str().unwrap(); // 将 HeaderValue 转换为 &str
        json_headers[name_str] = json!(value_str);
    }

    let json_string = serde_json::to_string(&json_headers).unwrap();
    json_string
}
#[tauri::command]
pub fn md5_str(str: String)->String{
    let sign = http::md5_str((str+"*^#n+kup;=").as_str());
    sign
}

#[tauri::command]
pub async fn fetch(url: String,method:String,data: Option<HashMap<String,String>>,headers:Option<HashMap<String,String>>,mac: Option<String>)->String{

    let mut header_map = HeaderMap::new();
    if let Some(h) = headers {
        for (name, value) in h.iter() {
            let name_str: HeaderName = (*name).parse().unwrap();
            let value_str: HeaderValue = (*value).parse().unwrap(); // 将 HeaderValue 转换为 &str
            header_map.insert(name_str, value_str);
        }
    }
    let mut datas:Option<_> = None;
    let mut data_map = HashMap::new();
    let dd_map;
    if let Some(d_map) = data{
        dd_map = d_map;
        for (name, value) in dd_map.iter() {
            let name_str = (*name).as_str();
            let value_str = (*value).as_str(); // 将 HeaderValue 转换为 &str
            data_map.insert(name_str, value_str);
        }
        datas = Some(data_map);
    }
    let mac_str;
    let mm;
    if let Some(m) = mac {
        mm = m;
        mac_str =Some( mm.as_str());
    }else{
        mac_str = None;
    }
    let fetch_rst = http::fetch(url.as_str(), method.as_str(),datas,Some(header_map),false,mac_str,None).await;
    match fetch_rst {
        Ok(r)=> r,
        Err(e)=>e.to_string()
    }
}
#[tauri::command]
pub async fn get_mac(org_code: String,term:String)->String{
    let mac_rst = service::login::get_pre_login_mac(org_code.as_str(),term.as_str()).await;
    match mac_rst {
        Ok(r)=> r,
        Err(e)=>e.to_string()
    }
}

#[tauri::command]
pub async fn yzg_login(_app: AppHandle,user_name:String,pwd:String,term:Option<String>,app_data_path:Option<String>)->String{
    let tt ;
    let t;
    if let Some(t_t) = term {
        t = t_t;
        tt = Some(t.as_str())
    }else{
        tt = None;
    }
    let result = service::login::yzg_login(user_name.as_str(),pwd.as_str(),tt,app_data_path).await;
    match result {
        Ok(r)=> r,
        Err(e)=>e.to_string()
    }
}
#[tauri::command]
pub async fn logout(app: AppHandle)->String{
    data_util::store_delete_data(app,"current_user".to_string());
    "success".to_string()
}
// #[tauri::command]
// pub fn get_goods_list_page(token: &str,keywords: &str,page_num:&str)->String{
//     let future = http_util::goods::goods_page_list(token,keywords,page_num);
//     let rst = executor::block_on(future);
//     match rst {
//         Ok(r)=>serde_json::to_string(&r).unwrap(),
//         Err(e)=>e.to_string()
//     }
// }

// #[tauri::command]
// pub fn get_order_list_page(token: &str,page_num:&str)->String{
//     let future = http_util::order::order_page_list(token,page_num);
//     let rst = executor::block_on(future);
//     match rst {
//         Ok(r)=>serde_json::to_string(&r).unwrap(),
//         Err(e)=>e.to_string()
//     }
// }

// #[tauri::command]
// pub fn create_order(token: String,merchant_id:String,item_id:String,item_num:String)->String{
//     let future = http_util::goods::create_order(token.as_str(),merchant_id.as_str(),item_id.as_str(),item_num.as_str());
//     let rst = executor::block_on(future);
//     match rst {
//         Ok(r)=>serde_json::to_string(&r).unwrap(),
//         Err(e)=>e.to_string()
//     }
// }
// #[tauri::command]
// pub async fn open_order_pay_window(app: tauri::AppHandle,page_url: String,token:String,order_no:String) {
//     let future = http_util::order::open_order_pay_window(app,page_url,token,order_no);
//     let _rst = executor::block_on(future);
//     // match rst {
//     //     Ok(r)=>serde_json::to_string(&r).unwrap(),
//     //     Err(e)=>e.to_string()
//     // }
// }

// #[tauri::command]
// pub fn get_order_pay_url(token:String,order_no:String)->String{
//     let future = http_util::order::get_order_pay_url(token.as_str(),order_no.as_str());
//     let rst = executor::block_on(future);
//     match rst {
//         Ok(r)=>serde_json::to_string(&r).unwrap(),
//         Err(e)=>e.to_string()
//     }
// }
// #[tauri::command]
// pub fn get_token()->String{
//     let future = http_util::goods::get_token();
//     let rst = executor::block_on(future);
//     match rst {
//         Ok(r)=>serde_json::to_string(&r).unwrap(),
//         Err(e)=>e.to_string()
//     }
// }


// #[tauri::command]
// pub fn get_mac()->String{
//     utils::sys_info::mac_addr().replace(":", "")
// }

// #[tauri::command]
// pub fn get_ip()->String{
//     utils::sys_info::get_local_ip()
// }

// #[tauri::command]
// pub fn get_net_ip()->String{
//     utils::sys_info::GEOData::get_ip()
// }

// #[tauri::command]
// pub fn get_os_name()->String{
//     let mut sys = System::new_all();
//     sys.refresh_all();

//     println!("System name:             {:?}", System::name());
//     println!("System kernel version:   {:?}", System::kernel_version());
//     println!("System OS version:       {:?}", System::os_version());
//     println!("System host name:        {:?}", System::host_name());

//     let os_name = System::name();
//     // println!("System name:             {:?}", os_name);
//     let os_name =  match os_name {
//         Some(n)=>n,
//         None=>"NO".to_string()
//     };
//     os_name
// }

// #[tauri::command]
// pub fn bind_or_get_shop_code(shop_code: Option<String>)->String{
//     info!("bind_or_get_shop_code {:?}",shop_code);
//     let data_dir = dirs_next::data_local_dir().unwrap().join("shop_code.txt");
//     let path_str = data_dir.as_path().to_str().unwrap();
//     let path = std::path::Path::new(path_str);
//     let metadata = std::fs::metadata(path);
//     let date = std::time::SystemTime::now();
//     let duration = date.duration_since(std::time::SystemTime::UNIX_EPOCH);
//     if let Some(c) = shop_code.clone() {
//         if c == "-999" {
//             let _ = std::fs::write(path, "");
//             return "clear".to_string()
//         }
//     }
//     let milliseconds = duration.unwrap().as_secs();
//     // let datetime = chrono::DateTime::from(date);
//     let d = match metadata {
//         Ok(metadata) => {
//             let s = std::fs::read_to_string(path);
//             let o_code = s.unwrap();
//             if let Some(c) = shop_code {
//                 if o_code == c {
//                     o_code
//                 }else {
//                     let _ = std::fs::write(path, c);
//                     "".to_string()
//                 }
//             }else {
//                 o_code
//             }

//         },
//         Err(_) => {
//             if let Some(c) = shop_code {
//                 let _ = std::fs::File::create(path);
//                 let _ = std::fs::write(path, c);
//             }
//             "".to_string()
//         },
//     };
//     d
// }

// #[tauri::command]
// pub fn encrypt(text: String,key: String)->String{
//     let key_b = key.as_bytes().try_into().unwrap();
//    utils::crypt_util::encrypt(text, key_b)
// }


// #[tauri::command]
// pub fn author_info()->String{
//     let mac = get_mac();
//     let data_dir = dirs_next::data_local_dir().unwrap().join(mac+".txt");
//     let path_str = data_dir.as_path().to_str().unwrap();
//     let path = std::path::Path::new(path_str);
//     let metadata = std::fs::metadata(path);
//     let date = std::time::SystemTime::now();
//     let duration = date.duration_since(std::time::SystemTime::UNIX_EPOCH);
//     let milliseconds = duration.unwrap().as_secs();
//     // let datetime = chrono::DateTime::from(date);
//     let d = match metadata {
//         Ok(metadata) => {
//             // TODO 内容改为时间加日期计数，避免修改系统时间或者找到该文件后手动修改
//             let s = std::fs::read_to_string(path);
//             info!("file exist data {:?} metadata {:?}",s,metadata);
//             let _ = std::fs::write(path, milliseconds.to_string());
//             let tmp:u64 = (s.unwrap()).parse().unwrap();
//             (milliseconds - tmp) as u32
//         },
//         Err(_) => {
//             let _ = std::fs::File::create(path);
//             let s = std::fs::read_to_string(path);
//             let _ = std::fs::write(path, milliseconds.to_string());
//             0 as u32
//         },
//     };
//     let total = 31 * 86400;
//     if d == 0 {
//         "30".to_string()
//     }else {
//         ((total - d)/86400).to_string()
//     }
// }
